package algorithm;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * User: Asuka
 * Date: 11-4-1
 * Time: 下午8:16
 */
public class AnotherPerm {

    public static void main(String[] args) {
        AnotherPerm perm = new AnotherPerm();
        Set set = new HashSet();
        int[] array = {1, 2, 2, 3, 4, 5};
        perm.perm(array, 0, array.length - 1, set);
        perm.exclude(set);
        for (Iterator iter = set.iterator(); iter.hasNext();) {
            System.out.println(iter.next());
        }
    }

    public void perm(int[] array, int left, int right, Set result) {
        if (left == right) {
            StringBuilder buff = new StringBuilder();
            for (int i : array) {
                buff.append(i);
            }
            result.add(buff.toString());
            return;
        }
        for (int i = left; i <= right; i++) {
            swap(array, i, left);
            perm(array, left + 1, right, result);
            swap(array, i, left);
        }
    }

    private void swap(int[] array, int left, int right) {
        if (left == right) return;
        int temp = array[left];
        array[left] = array[right];
        array[right] = temp;
    }

    public void exclude(Set set) {
        for (Iterator iter = set.iterator(); iter.hasNext();) {
            String s = (String) iter.next();
            if (s.contains("35") || s.contains("53") || s.indexOf("4") == 2)
                iter.remove();
        }
    }

}
